package com.scorpio.framework.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.scorpio.common.core.domain.entity.SysUser;
import com.scorpio.security.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 公共字段，自动填充值
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_BY = "createBy";
    private final static String CREATE_TIME = "createTime";
    private final static String UPDATE_TIME = "updateTime";
    private final static String UPDATE_BY = "updateBy";
    private final static String DEPT_ID = "deptId";

    @Override
    public void insertFill(MetaObject metaObject) {
        SysUser loginUser = null;
        try {
            loginUser = SecurityUtils.getLoginUser().getUser();
        } catch (Exception e) {
            loginUser = new SysUser();
        }

        //更新时间
        setFieldValByName(CREATE_TIME, new Date(), metaObject);
        //更新人姓名
        setFieldValByName(CREATE_BY, "" + loginUser.getUserId(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        SysUser loginUser = null;
        try {
            loginUser = SecurityUtils.getLoginUser().getUser();
        } catch (Exception e) {
            loginUser = new SysUser();
        }

        setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        //更新人姓名
        setFieldValByName(UPDATE_BY, "" + loginUser.getUserId(), metaObject);
    }
}
